<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'
import html2canvas from 'html2canvas'

// 背景大图
let bigBase64 = ref('')
const upBaseImgFn = (e) => {
  // console.log(e.target.files[0])
  let f = e.target.files[0]
  let filereader = new FileReader();
  filereader.onload = function (event) {
    bigBase64.value = event.target.result;
  };
  filereader.readAsDataURL(f);
}

// 小图片
let smallBase64 = ref('')
const upSmallImgFn = (e) => {
  // console.log(e.target.files[0])
  let f = e.target.files[0]
  let filereader = new FileReader();
  filereader.onload = function (event) {
    smallBase64.value = event.target.result;
  };
  filereader.readAsDataURL(f);
}

// 下载
let bigWrapRef = ref('')
const downImg = () => {
  console.log(html2canvas(bigWrapRef.value))

  html2canvas(bigWrapRef.value).then(imgbase64 => {
    console.log(imgbase64)
    // .toDataURL()方法是返回一个包含图片展示的 数据URL。可以使用 type 参数其类型
    // .toDataURL(type, encoderOptions);
    let imgUrl = imgbase64.toDataURL("image/png")
    var a = document.createElement('a')
    a.setAttribute('href', imgUrl)
    a.setAttribute('download', 'xxx.png')
    a.click()
    URL.revokeObjectURL(imgUrl)
  })
}

</script>

<template>
  <h1 style="text-align:center">合并多张图片、下载</h1>
  <div>
    <span>上传背景大图片：</span>
    <input type="file" @change="upBaseImgFn" />
  </div>
  <div>
    <span>上传小图片：</span>
    <input type="file" @change="upSmallImgFn" />
  </div>

  <!-- 图片容器 -->
  <div class="bigWrap" ref="bigWrapRef">
    <img class="bgImg" :src="bigBase64" alt="">

    <div class="smallWrap">
      <img class="smallPic" :src="smallBase64" alt="">
    </div>
  </div>

  <div>
    <button @click="downImg">下载合并图片</button>
  </div>
</template>

<style scoped>
div {
  margin: 10px 0;
}

.bigWrap {
  width: 400px;
  height: 400px;
  position: relative;
  border: 1px solid #000;
}

img.bgImg {
  width: 100%;
  height: 100%;
}

div.smallWrap {
  width: 100px;
  height: 100px;
  position: absolute;
  top: 30px;
  left: 30px;
  z-index: 9;
  overflow: hidden;
  border: 2px solid rgb(197, 21, 21);
}

div.smallWrap img.smallPic {
  width: 100%;
  height: 100%;
}
</style>